<?php

require_once 'View.php';
require_once 'Checker.php';

class PhpTemplate extends View{

    private $data = null;
    private $template = null;

    public function __construct($template){
        self::checkTemplate($template);
        $this->data = array();
        $this->setTemplate($template);
    }

    public function getData(){return $this->data;}
    public function getTemplate(){return $this->template;}

    public function setData($data){
        Checker::checkArray($data);
        $this->data = $data;
    }

    public function addData($data){
        Checker::checkArray($data);
        foreach($data as $name => $value)$this->addValue($name, $value);
    }

    public function setTemplate($template){
        self::checkTemplate($template);
        $this->template = $template;
    }

    public function setValue($name, $value){
        Checker::checkString($name);
        $this->data[$name] = $value;
    }

    public function getValue($name){
        Checker::checkString($name);
        if(isset($this->data[$name]))return $this->data[$name];
        return null;
    }

    public function hasValue($name){
        Checker::checkString($name);
        return isset($this->data[$name]);
    }

    public function deleteValue($name){
        Checker::checkString($name);
        if(isset($this->data[$name]))unset($this->data[$name]);
    }

    public function render(){
        foreach($this->data as $_name_ => &$value)
            $$_name_ = $value;
        include "views/$this->template.php";
    }

    // --- error checking

    private static function checkTemplate($template){
        if(Checker::isEnabled() && (!is_string($template) || trim($template) == "" || !file_exists("views/$template.php")))
            throw new InvalidArgumentException ("invalid template", null, null);
    }

}
?>
